package com.ms.orm.context;


import com.ms.orm.annotation.DbType;
import com.ms.orm.dboperator.DefaultDbOperator;
import com.ms.orm.meta.EntityAndTableInfo;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zdh
 * 存储 entity 元数据、entity对于的基础数据操作，即简单的单表曾删改查
 */
public class DefaultLittleOrmContext implements LittleOrmContext {

    private DefaultLittleOrmContext(){}

    /**
     * 全局单实例，不可修改，这样相对安全， 不会因为中途修改引用导致 加载的元数据失效
     */
    private static final  DefaultLittleOrmContext INSTANCE = new DefaultLittleOrmContext();

    public final static DbType dbType = null;

    public static DefaultLittleOrmContext getDefaultLittleOrmContext(){
        return INSTANCE;
    }

    /**
     * key = entityClass
     * value = EntityAndTableInfo
     */
    private static final Map<Class<?>, EntityAndTableInfo> ENTITY_TABLE_INFO_MAP = new HashMap<>();

    /**
     * key = entityClass
     * value = DefaultDbOperator
     */
    private static final Map<Class<?>, DefaultDbOperator> DEFAULT_DB_OPERATOR_MAP = new HashMap<>();

    public  String getTableName(Class<?> clazz) {
        return getEntityAndTableInfo(clazz).getTableName();
    }


    public  void addEntityAndTableInfo(EntityAndTableInfo entityAndTableInfo){
        ENTITY_TABLE_INFO_MAP.put(entityAndTableInfo.getEntityClass(),entityAndTableInfo);
    }

    public EntityAndTableInfo getEntityAndTableInfo(Class entityClass){
        return ENTITY_TABLE_INFO_MAP.get(entityClass);
    }

    /**
     * DefaultDbOperator 根据 entity 对象生成，可以重复生成，可以不考虑线程安全问题
     * @param entityClass
     * @return
     */
    public DefaultDbOperator getDefaultDbOperator(Class entityClass){
        DefaultDbOperator dbOperator = DEFAULT_DB_OPERATOR_MAP.get(entityClass);
        if(dbOperator==null){
            EntityAndTableInfo entityAndTableInfo = ENTITY_TABLE_INFO_MAP.get(entityClass);
            dbOperator = new DefaultDbOperator(getJdbcTemplate(),entityAndTableInfo.getEntityClass(),entityAndTableInfo.getTableName());
            DEFAULT_DB_OPERATOR_MAP.put(entityClass,dbOperator);
        }
        return dbOperator;
    }

    public DefaultDbOperator getDefaultDbOperator(Object entity){
        return getDefaultDbOperator(entity.getClass());
    }


    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}
